package elitech.vietnam.copyweatherfashion;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;

import org.xmlpull.v1.XmlPullParserException;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.URLUtil;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import elitech.vietnam.copyweatherfashion.config.Config;
import elitech.vietnam.copyweatherfashion.config.Const;
import elitech.vietnam.copyweatherfashion.config.Options;
import elitech.vietnam.copyweatherfashion.dialog.ProgressDialogFragment;
import elitech.vietnam.copyweatherfashion.utilities.Utilities;
import elitech.vietnam.copyweatherfashion.widget.ScaleImageView;
import elitech.vietnam.copyweatherfashion.wsclient.ImageUploader;
import elitech.vietnam.copyweatherfashion.wsclient.Service;
import eu.janmuller.android.simplecropimage.CropImage;

public class CreatePostActivity extends FragmentActivity {

	public static final String	EXTRA_TYPE			= "EXTRA_TYPE";
	public static final String	EXTRA_IMAGEPATH		= "EXTRA_IMAGEPATH";
	public static final String	EXTRA_REQUESTCODE	= "EXTRA_REQUESTCODE";
	public static final String	EXTRA_TEMPIMAGE		= "EXTRA_TEMPIMAGE";
	public static final String	EXTRA_USERID		= "EXTRA_USERID";
	public static final String	EXTRA_POSTID		= "EXTRA_POSTID";
	public static final String	EXTRA_POSTCONTENT	= "EXTRA_POSTCONTENT";
	public static final String	EXTRA_POSTIMAGE		= "EXTRA_POSTIMAGE";

	private static final int	REQUEST_CROP		= 1;

	public static enum CreateType {
		CREATE, EDIT, CROPPED
	}

	Options	mOptions;
	Config mConfig;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_create_post);

		mConfig = new Config(this);
		
		if (savedInstanceState == null) {
			getSupportFragmentManager().beginTransaction().add(R.id.container, new PlaceholderFragment()).commit();
		}
	}

	/**
	 * A placeholder fragment containing a simple view.
	 */
	public static class PlaceholderFragment extends Fragment implements View.OnClickListener {

		CreatePostActivity		mActivity;

		Button					mBtnBack, mBtnSave;
		TextView				mTxtTitle;
		ScaleImageView			mImgContent;
		ImageButton				mBtnCrop;
		EditText				mEdtContent;

		String					mImagePath		= "";
		String					mImageTemp		= "";
		String					mPostImage		= "";
		int						mPostId			= 0;
		String					mPostContent	= "";
		int						mRequestCode	= 0;
		int						mUserId			= 0;
		
		boolean					mCropResult		= false;

		CreateType					mType;

		ProgressDialogFragment	mProgress;

		public PlaceholderFragment() {
		}

		@Override
		public void onCreate(Bundle savedInstanceState) {
			super.onCreate(savedInstanceState);
			mActivity = (CreatePostActivity) getActivity();
			mImagePath = mActivity.getIntent().getStringExtra(EXTRA_IMAGEPATH);
			mPostId = mActivity.getIntent().getIntExtra(EXTRA_POSTID, 0);
			mPostContent = mActivity.getIntent().getStringExtra(EXTRA_POSTCONTENT);
			mPostImage = mActivity.getIntent().getStringExtra(EXTRA_POSTIMAGE);
			mImageTemp = mActivity.getIntent().getStringExtra(EXTRA_TEMPIMAGE);
			mRequestCode = mActivity.getIntent().getIntExtra(EXTRA_REQUESTCODE, 0);
			mUserId = mActivity.getIntent().getIntExtra(EXTRA_USERID, 0);
			mType = (CreateType) mActivity.getIntent().getSerializableExtra(EXTRA_TYPE);
			if (mType == CreateType.CREATE && (mImagePath == null || mRequestCode == 0 || mImageTemp == null || mUserId == 0))
				throw new NullPointerException(
						"Must put EXTRA_TEMPIMAGE, EXTRA_USERID, EXTRA_IMAGEPATH and EXTRA_REQUESTCODE when launch activity");
			else if (mType == CreateType.EDIT
					&& (mPostId == 0 || mRequestCode == 0 || mImageTemp == null || mUserId == 0 || mPostContent == null || mPostImage == null))
				throw new NullPointerException(
						"Must put EXTRA_TEMPIMAGE, EXTRA_USERID, EXTRA_POSTCONTENT, EXTRA_POSTID, mPostImage and EXTRA_REQUESTCODE when launch activity");
		}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
			View view = inflater.inflate(R.layout.fragment_create_post, container, false);

			mBtnBack = (Button) view.findViewById(R.id.newpost_btnBack);
			mBtnCrop = (ImageButton) view.findViewById(R.id.newpost_btnCrop);
			mBtnSave = (Button) view.findViewById(R.id.newpost_btnSave);
			mEdtContent = (EditText) view.findViewById(R.id.newpost_edtContent);
			mImgContent = (ScaleImageView) view.findViewById(R.id.newpost_imgContent);
			mTxtTitle = (TextView) view.findViewById(R.id.newpost_txtTitle);

			mBtnBack.setOnClickListener(this);
			mBtnCrop.setOnClickListener(this);
			mBtnSave.setOnClickListener(this);

			return view;
		}

		@Override
		public void onActivityCreated(Bundle savedInstanceState) {
			super.onActivityCreated(savedInstanceState);
			mProgress = new ProgressDialogFragment.Builder().setMessage(getString(R.string.please_wait))
					.setTitle(getString(R.string.loading)).build();
		}

		@Override
		public void onActivityResult(int requestCode, int resultCode, Intent data) {
			super.onActivityResult(requestCode, resultCode, data);
			if (requestCode == REQUEST_CROP && resultCode == RESULT_OK) {
				mImagePath = data.getStringExtra(CropImage.IMAGE_PATH);
				mCropResult = true;
			}
		}

		@Override
		public void onResume() {
			super.onResume();
			new AsyncTask<Integer, Integer, Boolean>() {
				@Override
				protected void onPreExecute() {
					mProgress.show(getFragmentManager());
				}

				@Override
				protected Boolean doInBackground(Integer... params) {
					try {
						if (!mCropResult) {
							if ((URLUtil.isContentUrl(mImagePath) || URLUtil.isHttpsUrl(mImagePath) || URLUtil.isHttpUrl(mImagePath)) && mType == CreateType.CREATE) {
								mImagePath = Utilities.downloadImage(mActivity, mImagePath, mImageTemp);
							} else if (mType == CreateType.EDIT) {
								mImagePath = Utilities.downloadImage(mActivity, Const.SERVER_IMAGE_URL + mPostImage, mImageTemp);
							}
						}
						int rotation = Utilities.getImageRotation(mImagePath);
						if (rotation != 0) {
							Bitmap bitmap = BitmapFactory.decodeFile(mImagePath);
							Matrix matrix = new Matrix();
							matrix.postRotate(rotation);
							Bitmap bitmap1 = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix,
									false);
							bitmap.recycle();
							FileOutputStream out = new FileOutputStream(mImageTemp);
							bitmap1.compress(Bitmap.CompressFormat.JPEG, Const.IMAGE_COMPRESSION, out);
							out.close();
							bitmap.recycle();
							mImagePath = mImageTemp;
						}
					} catch (IOException | OutOfMemoryError e) {
						e.printStackTrace();
						return false;
					}
					return true;
				}

				@Override
				protected void onPostExecute(Boolean result) {
					if (!result) {
						Toast.makeText(mActivity, "Error loading data. Please try again", Toast.LENGTH_LONG).show();
						mActivity.setResult(RESULT_CANCELED);
						mActivity.finish();
					} else {
						displayContentImage(mImagePath);
						if (mType == CreateType.EDIT)
							mEdtContent.setText(mPostContent);
					}
					mProgress.dismiss();
				}
			}.execute();
		}
		
		@Override
		public void onDestroy() {
			super.onDestroy();
		}

		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.newpost_btnCrop:
				mPostContent = mEdtContent.getText().toString();
				Intent intent = new Intent(mActivity, CropImage.class);
				intent.putExtra(CropImage.IMAGE_PATH, mImagePath);
				intent.putExtra(CropImage.SCALE, true);
				intent.putExtra(CropImage.ASPECT_X, 0);
				intent.putExtra(CropImage.ASPECT_Y, 0);
				startActivityForResult(intent, REQUEST_CROP);
				break;
			case R.id.newpost_btnBack:
				mActivity.onBackPressed();
				break;
			case R.id.newpost_btnSave:
				switch (mType) {
				case CREATE:
					new NewPostTask().execute();
					break;
				case EDIT:
					new UpdatePostTask().execute();
					break;
				default:
					break;
				}
				break;
			default:
				break;
			}
		}
		
		private void displayContentImage(String path) {
			try {
				BitmapFactory.Options options = new BitmapFactory.Options();
				options.inJustDecodeBounds = true;
				BitmapFactory.decodeFile(path, options);
				int width = options.outWidth;
				int sampleSize = 1;
				while (width/sampleSize > mActivity.mConfig.getScreenWidth())
					sampleSize *= 2;
				options.inSampleSize = sampleSize;
				options.inJustDecodeBounds = false;
				Bitmap bitmap = BitmapFactory.decodeFile(path, options);
				mImgContent.setImageBitmap(bitmap);
			} catch (OutOfMemoryError e) {
				e.printStackTrace();
			}
		}

		class NewPostTask extends AsyncTask<Integer, Integer, Boolean> {
			int rs = -1;
			@Override
			protected void onPreExecute() {
				mProgress.show(getFragmentManager());
			}

			@Override
			protected Boolean doInBackground(Integer... params) {
				String imgName = mUserId + "_" + System.currentTimeMillis() + ".jpg";
				boolean uploaded = false;
				uploaded = new ImageUploader().upload(mImagePath, Const.MEMBER_FOLDER + imgName);

				if (uploaded) {
					Calendar cal = Calendar.getInstance();
					int day = cal.get(Calendar.DATE);
					int mon = cal.get(Calendar.MONTH) + 1;
					int yea = cal.get(Calendar.YEAR);
					String title = mUserId + " Style " + cal.getTime().toString();
					String content = mEdtContent.getText().toString().trim();
					try {
						rs = new Service().createNewPost(mUserId, yea, mon, day, title, "0", "", Const.MEMBER_FOLDER
								+ imgName, content);
					} catch (IOException | XmlPullParserException e) {
						e.printStackTrace();
					}
				}
				return rs > 0;
			}

			@Override
			protected void onPostExecute(Boolean result) {
				if (result) {
					new AsyncTask<Integer, Integer, Boolean>() {
						@Override
						protected Boolean doInBackground(Integer... params) {
							try {
								new Service().notifyFriendPost(rs);
							} catch (IOException | XmlPullParserException e) {
								e.printStackTrace();
							}
							return null;
						}
					}.execute();
					Toast.makeText(mActivity, getString(R.string.newpost_success), Toast.LENGTH_SHORT).show();
					mActivity.setResult(RESULT_OK);
				} else {
					Toast.makeText(mActivity, getString(R.string.newpost_failed), Toast.LENGTH_SHORT).show();
					mActivity.setResult(RESULT_CANCELED);
				}
				mProgress.dismiss();
				mActivity.finish();
			}
		}

		class UpdatePostTask extends AsyncTask<Integer, Integer, Boolean> {
			protected void onPreExecute() {
				mProgress.show(getFragmentManager());
			}

			@Override
			protected Boolean doInBackground(Integer... params) {
				String imgName = mUserId + "_" + System.currentTimeMillis() + ".jpg";
				boolean uploaded = false;
				uploaded = new ImageUploader().upload(mImagePath, Const.MEMBER_FOLDER + imgName);

				int rs = -1;
				if (uploaded) {
					String content = mEdtContent.getText().toString().trim();
					try {
						rs = new Service().updatePost(mUserId, mPostId, content, Const.MEMBER_FOLDER + imgName);
					} catch (IOException | XmlPullParserException e) {
						e.printStackTrace();
					}
				}
				return rs > 0;
			}

			@Override
			protected void onPostExecute(Boolean result) {
				if (result) {
					Toast.makeText(mActivity, R.string.editpostsuccess, Toast.LENGTH_SHORT).show();
					Intent intent = new Intent();
					intent.putExtra(EXTRA_POSTID, mPostId);
					mActivity.setResult(RESULT_OK, intent);
				} else {
					Toast.makeText(mActivity, R.string.newpost_failed, Toast.LENGTH_SHORT).show();
					mActivity.setResult(RESULT_CANCELED);
				}
				mProgress.dismiss();
				mActivity.finish();
			}
		}
	}
}
